<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Services\ImageUrlService;

class AdImage extends Model
{
    use SoftDeletes;

    /**
     * 关联的数据表
     */
    protected $table = 'ims_yz_ad_images';

    /**
     * 可以批量赋值的属性
     */
    protected $fillable = [
        'title',
        'image_path',
        'url',
        'position_id',
        'sort_order',
        'status',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    /**
     * 属性类型转换
     */
    protected $casts = [
        'position_id' => 'integer',
        'sort_order' => 'integer',
        'status' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime'
    ];

    /**
     * 获取图片完整URL
     */
    public function getFullImageUrlAttribute()
    {
        if (empty($this->image_path)) {
            return '';
        }
        
        // 如果已经是完整URL，直接返回
        if (strpos($this->image_path, 'http') === 0) {
            return $this->image_path;
        }
        
        // 使用统一的图片URL处理函数
        return ImageUrlService::processImageUrl($this->image_path);
    }

    /**
     * 根据位置查询广告图片
     */
    public function scopeByPosition($query, $positionId)
    {
        return $query->where('position_id', $positionId);
    }

    /**
     * 查询激活的广告图片
     */
    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    /**
     * 按排序查询
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc');
    }
}
